<script lang="tsx" setup>
import type { TableProps } from 'tdesign-vue-next'
// import { data } from './helper'
const { ipcRenderer } = require('electron')

const EditDialog = defineAsyncComponent(() => import('./componenets/editDialog.vue'))

const EditDialogRef = ref<typeof EditDialog>()

const tableData = ref<any[]>([])

const columns: TableProps['columns'] = [
  {
    colKey: 'platformName',
    title: '平台名称',
    align: 'center'
  },
  {
    colKey: 'platformUrl',
    title: '抢票网址',
    align: 'center',
    ellipsis: true
  },
  {
    colKey: 'platformAccount',
    title: '账户名称',
    align: 'center',
    ellipsis: true
  },
  {
    colKey: 'operation',
    title: '操作',
    align: 'center',
    fixed: 'right',
    width: 240,
    cell: (h, { row, rowIndex }) => {
      return (
        <div class="flex gap-2">
          <t-button theme="primary" variant="text" onClick={() => handleEnter(row)}>
            进入平台
          </t-button>{' '}
          <t-button theme="success" variant="text" onClick={() => handleLogin()}>
            登陆
          </t-button>
          <t-button
            theme="warning"
            variant="text"
            onClick={() => handleEdit(rowIndex, row as TableRowData)}
          >
            编辑
          </t-button>
        </div>
      )
    }
  }
]

function getTableData() {
  ipcRenderer.send('getTableData')
  ipcRenderer.on('responseTableData', (event, data) => {
    const realData = Array.isArray(data) ? data : JSON.parse(data)
    console.log('收到主进程的响应数据:', data, 1111111, realData)
    tableData.value = realData
  })
}

onMounted(() => {
  getTableData()
})

async function handleLogin() {
  try {
    await ipcRenderer.send('createNewPage')
    await ipcRenderer.send('login')
  } catch (error) {
    console.log('error', error)
  }
  console.log('handleLogin')
}

function handleEnter(row: any) {
  console.log('handleDetail', row)
}

function handleEdit(index?: number, row?: TableRowData) {
  EditDialogRef.value?.open(tableData.value, index, row)
}

function onRefreshTable() {
  getTableData()
}
</script>

<template>
  <div class="w-full">
    <EditDialog ref="EditDialogRef" @refresh="onRefreshTable" />
    <div class="flex justify-end">
      <t-button theme="success" @click="handleEdit()">新增</t-button>
    </div>
    <div class="flex justify-center">
      <t-table row-key="id" :columns="columns" :data="tableData"> </t-table>
    </div>
  </div>
</template>

<style></style>
